/**
 * Created by Administrator on 2018/3/21.
 */
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
    Image,
    Platform,
    StyleSheet,
    Text,
    View,
    Dimensions,
    TouchableOpacity
} from 'react-native';

const {width,heigth} = Dimensions.get("window");

const thirdWidth = width / 3;

const imageWidth = thirdWidth - 10 * 2;

const imageHeight = imageWidth / 0.697;

const styles = StyleSheet.create({
    item:{
        marginTop:20,
        width:imageWidth,
        marginLeft:15,
    },
    image:{
        width:imageWidth,
        height:imageHeight,
    },
    title:{
        marginTop:5,
        fontSize:20,
        fontWeight:'bold',
        textAlign:'center',
    },
    stars:{
        width:10,
        height:10,
    },
    starsWrapper:{
        flexDirection:'row',
    }
})
//1.传统组件写法
// export default class Item extends Component {
//     render() {
//         const {title,image} = this.props;
//         return (
//             <View style={styles.item}>
//                 <Image source={{uri:image}} style={styles.image}/>
//                 <Text numberOfLines={1} style={styles.title}>{title}</Text>
//             </View>
//         );
//     }
// }

//2.无状态组件(在没有state的情况下),性能更优
const Item = (props) =>{
    const {title,image,stars,onPress} = props;
    return (
        <TouchableOpacity style={styles.item} onPress={onPress}>
            <Image source={{uri:image}} style={styles.image}/>
            <Text numberOfLines={1} style={styles.title}>{title}</Text>
            {renderStars(stars)}
        </TouchableOpacity>
    );
};

const renderStars = (stars)=>{
    if (stars === '00') {
        return (<Text>暂无评分</Text>);
    }

    const total =5;
    let full, half, empty;
    full = parseInt(stars[0]) - 1;
    if (stars[1] === '5') {
        full++;
        half = 0;
        empty = total - full;
    } else {
        half = 1;
        empty = total - full - half;
    }
    const arr =[];
    let i;
    for(i=0;i<full;i++){
        arr.push(<Image key={i}
                        style={styles.stars}
                        source={require('../img/star-full.png')}
        />);
    }

    if(half){
        arr.push(<Image key={i}
                        style={styles.stars}
                        source={require('../img/star-half.png')}
        />);
    }
    for (let j = 0; j < empty; j++) {
        arr.push(
            <Image
                key={i+j+1}
                style={styles.stars}
                source={require('../img/star-empty.png')}
            />
        );
    }
    return (
        <View style={styles.starsWrapper}>
            {arr}
        </View>
    );
};
export default Item